import re

from rest_framework import serializers

from areas.models import Area

from users.models import Address


class AreasSerializers(serializers.ModelSerializer):

    class Meta:

        model = Area
        fields = '__all__'


class AddressSerializers(serializers.ModelSerializer):

    # 显示指明字段
    city_id = serializers.IntegerField(min_value=1, write_only=True)
    district_id = serializers.IntegerField(min_value=1, write_only=True)
    province_id = serializers.IntegerField(min_value=1, write_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)


    class Meta:

        model = Address
        exclude = ('user', )

    # 验证手机号格式
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    # 重写父类方法
    def create(self, validated_data):

        # 需要在验证数据后添加user
        user = self.context['request'].user

        validated_data['user'] = user
        address = super().create(validated_data)

        return address